import io from "socket.io-client";
import axios from 'axios'
const socket = io('ws://localhost:9093');

const MSG_LIST = 'MSG_LIST';
const MSG_RECV = 'MSG_RECV';
const MSG_READ = 'MSG_READ';

const initState = {
    chatMsg:[],
    users:{},
    unread:0
}

export function chat(state = initState, action) {
    console.log(action)
    switch (action.type) {
        case MSG_LIST:
            return {...state, users: action.payload.users, chatMsg: action.payload.msgs, unread: action.payload.msgs.filter( v=> !v.read&&v.to===action.payload.userid).length}
        case MSG_RECV:
            const n = action.payload.to === action.userid ? 1 : 0
            return {...state, chatMsg: [...state.chatMsg,action.payload], unread:state.unread + n}
        case MSG_READ:
            return {...state, chatMag:state.chatMsg.map(v=>{
                    if (v.from === action.payload.from) {
                        v.read= true
                    }
                    return v
                }), unread: state.unread - action.payload.num}
        default:
            return state;
    }
}
function msgList(msgs, users, userid) {
    return {type: MSG_LIST, payload: {msgs, users, userid}}
}
function msgRecv(msg, userid) {
    return {userid, type: MSG_RECV, payload: msg}
}
export function recvMsg() {
    return (dispatch, getState) => {
        socket.on('recvmsg', function(data) {
            const userid = getState().user._id
            dispatch(msgRecv(data, userid))
        })
    }
}
function msgRead({from, userid, num}) {
    console.log({from, userid, num})
    return {type: MSG_READ, payload: {from, userid, num}}
}

export function readMsg(from) {
    return (dispath, getState) => {
        axios.post('/user/readmsg', {from})
            .then(res => {
                console.log(res)
                const userid = getState().user._id
                if (res.status === 200 && res.data.code === 0) {
                    dispath(msgRead({userid, from, num: res.data.num}))
                }
            })
    }
}

export function getMsgList() {
    return (dispatch, getState) => {
        axios.get('/user/getMsgList')
            .then(res => {
                if (res.status === 200 && res.data.code === 0) {
                    const userid = getState().user._id
                    dispatch(msgList(res.data.msgs, res.data.users, userid))
                }
            })
    }
}

export function sendMsg({from, to, msg}) {
    return dispatch => {
        socket.emit('sendmsg', {from, to, msg})
    }
}